package ru.ifmo.lab3;

import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;

public class CockroachScheduler {
    private Integer vertexCount;
    private Integer cockroachCount;
    private Integer startVertex;
    private Integer finishVertex;

    private volatile Graph graph;
    private volatile CountDownLatch countDownLatch;

    public CockroachScheduler(String path) throws IOException, IllegalArgumentException {
        try (
                BufferedReader in = new BufferedReader(new FileReader(path))
        ) {
            String line = in.readLine();
            String[] initArgs =  line.split(" ");
            if (initArgs.length != 4) {
                throw new IllegalArgumentException("Input argument's count must be 4!");
            }

            vertexCount = Integer.parseInt(initArgs[0]);
            cockroachCount = Integer.parseInt(initArgs[1]);
            startVertex = Integer.parseInt(initArgs[2]);
            finishVertex = Integer.parseInt(initArgs[3]);

            startVertex--;
            finishVertex--;

            int vertexCounter = 0;
            graph = new Graph(vertexCount);
            countDownLatch = new CountDownLatch(cockroachCount);

            while ((line = in.readLine()) != null) {
                String[] vertexEdges = line.split(" ");
                if (vertexEdges.length % 2 != 0) {
                    throw new IllegalArgumentException("Incorrect description of edges!");
                }

                for (int i = 0; i < vertexEdges.length; i += 2) {
                    graph.addEdge(vertexCounter, Integer.parseInt(vertexEdges[i]) - 1, Integer.parseInt(vertexEdges[i + 1]));
                }

                ++vertexCounter;
            }
        }
    }

    public void printGraph() {
        for (int i = 0; i < vertexCount; ++i) {
            ArrayList<Edge> adjEdges = graph.getAdjEdges(i);
            String answer = Integer.toString(i) + ":";

            for (Edge edge : adjEdges) {
                answer += " [" + edge.getVertexTo() + ", " + edge.getCapacity() + "]";
            }

            System.out.println(answer);
        }
    }

    public void startRace() {

        for (int i = 0; i < cockroachCount; ++i)
            new Thread(new CockroachThread(graph, startVertex, finishVertex, i + 1, countDownLatch)).start();
        try {
            countDownLatch.await();
        }
        catch (InterruptedException e) {
            System.err.println(e.getMessage());
            Thread.currentThread().interrupt();
        }
    }
}
